<template>
  <el-container>
    <el-header>
      <h1 style="margin-top: auto">课程详情</h1>
    </el-header>
    <el-main :key="updateKey">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card>
            <h2>{{course.courseName}}</h2>
            <p>{{course.description}}</p>
            <el-divider></el-divider>
            <h3>课程目录
              <el-button size="small" style="float: right" @click="dialogDirectories=true">创建目录</el-button></h3>

            <el-tree :key="new Date().getTime()" ref="directoriesTree"
                :data="treeData"
                :props="defaultProps"
                node-key="id"
                default-expand-all
                :expand-on-click-node="false" @node-click="handleNodeClick"
                icon="Folder"
                style="max-width: 600px"
            >
              <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <span>
                      <a style="color:#409eff" @click="append(data)"> 创建 </a>
                      <a style="color:#409eff" @click="update(data)"> 修改 </a>
                      <a style="color:#f56c6c" @click="remove(node, data)"> 删除 </a>
                       <el-upload
                           :key="uploadKey"
                           ref="fileUploadBtn"
                           class="upload-demo"
                           :http-request="toUploadFile"
                           :limit="1"
                           :multiple="false"
                           :show-file-list="false"
                           element-loading-text="正在上传"
                           :on-success="handleUploadSuccess"
                           style="display: inline-flex"
                       >
        <a style="color:#409eff" @click="changeUploadDirectoryId(data)"> 上传文件 </a>
      </el-upload>

                    </span>
                  </span>
              </template>
            </el-tree>

          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <h3>课程基本信息</h3>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="讲师">{{course.nickname}}</el-descriptions-item>
              <el-descriptions-item label="创建课程时间">{{course.createdAt}}</el-descriptions-item>
<!--              <el-descriptions-item label="评分">-->
<!--                <el-rate v-model="course.rating" disabled></el-rate>-->
<!--              </el-descriptions-item>-->
            </el-descriptions>
          </el-card>
          <el-divider></el-divider>
          <el-card>
            <h3>课件列表</h3>
            <el-table :data="fileList" style="width: 100%" :show-header="false">
              <el-table-column prop="fileName" label="文件名" width="180" >
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-icon><Files /></el-icon>
                    <span style="margin-left: 10px">{{ scope.row.fileName }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="Operations">
                <template #default="scope">
                  <el-button
                      key="primary"
                      type="primary"
                      link
                      @click="previewFile(scope.row.fileId,scope.row.fileName)"
                  >
                    预览
                  </el-button>
                    <el-button
                        key="danger"
                        type="danger"
                        link
                        @click="deleteFile(scope.row.fileId)"
                    >
                      删除
                    </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>

  <el-dialog v-model="dialogDirectories" :title="titleName" width="1000">
    <el-form-item :label-width="200" label="目录名称">
      <el-input v-model="directoriesForm.directoryName" autocomplete="off"/>
    </el-form-item>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogDirectories = false">取消</el-button>
        <el-button v-if="!isUpdate" type="primary" @click="createDirectories()">
          提交
        </el-button>
        <el-button v-if="isUpdate" @click="updateDirectories()">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>




<script setup>
import courseAPI from "../../api/course.js";
import directoriesAPI from "../../api/directories.js";
import {onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router"
import {ElMessage} from "element-plus";
import fileApi from "../../api/file.js";
import {Files, Timer} from "@element-plus/icons-vue";
import Base64 from "qs/lib/utils.js";

const router = useRoute()
const vueRouter = useRouter();
const updateKey = ref(0);
let course=reactive({
})
const directoriesTree = ref(null);
let isUpdate = ref(false);
const dialogDirectories = ref(false);
let treeData = ref(null);
let titleName = ref("");
//列表
let directoriesForm = reactive({
  directoryId:'',
  courseId:'',
  directoryName:'',
  parentDirectoryId:'',
  createdAt:''
})
//文件列表
let fileList = ref(null);
onBeforeMount(async () => {
  let courseId = router.query.courseId;
  await getDetails(courseId);
  updateKey.value ++;
})
onMounted(() => {
  getTreeData();
})

const getTreeData = async () => {
  let courseId = router.query.courseId;
  directoriesAPI.list({"courseId":courseId}).then(res=>{
    if(res.data.code===200){
      treeData.value=res.data.data;
    }
  })
}

const getDetails =  async (id) => {
  await courseAPI.detailCourse({'courseId': id}).then((res) => {
    course = res.data.data;
  }).catch((err) => {
    console.log(err)
  });
}

//创建目录
const createDirectories = async () => {
  directoriesForm.courseId = router.query.courseId;
  await directoriesAPI.add(directoriesForm).then(res=>{
    if (res.data.code === 200) {
      ElMessage({
        message: '添加成功',
        type: 'success',
      })
      dialogDirectories.value = false;
      getTreeData();
      directoriesForm.directoryName = '';
      directoriesForm.parentDirectoryId = null;
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}

//更新课程目录
const updateDirectories = async () => {
  directoriesForm.courseId = router.query.courseId;
  await directoriesAPI.update(directoriesForm).then(res=>{
    if (res.data.code === 200) {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      dialogDirectories.value = false;
      getTreeData();
      directoriesForm.directoryName = '';
      directoriesForm.parentDirectoryId = null;
      isUpdate.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}

const append = (data) =>{
  directoriesForm.directoryId = null;
  directoriesForm.parentDirectoryId = data.id;
  titleName.value = "创建课程目录";
  dialogDirectories.value = true;
}

//更新课程目录
const update = (data) =>{
  directoriesForm.directoryId = data.id;
  directoriesForm.directoryName = data.name;
  dialogDirectories.value = true;
  isUpdate.value = true;
  titleName.value = "修改课程目录";
}

const defaultProps = {
  children: 'children',
  label: 'name',
}

//删除数据方法（跟官网一样，没变）
const remove = (node, data) => {
  directoriesAPI.delContent({"directoriesId":data.id}).then(res=>{
    if (res.data.code === 200) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      dialogDirectories.value = false;
      getTreeData();
      directoriesTree.value.remove(node);
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}
let uploadDirectoryId = ref(null);
const changeUploadDirectoryId = (data)=>{
  uploadDirectoryId.value = data.id;
}
let uploadKey = ref(0);
const toUploadFile = (param) => {
  console.log(param);
  const file = param.file;
  const formData = new FormData();
  formData.append('file', file);
  formData.append('directoryId',uploadDirectoryId.value);
  fileApi.uploadFile(formData).then(res => {
    if(res.data.code === 200){
      ElMessage.success("上传成功")
      fileApi.fileList({"directoryId":uploadDirectoryId.value}).then((res) => {
        if (res.data.code === 200){
          fileList.value = res.data.data;
          fileUploadBtn.value.clearFiles();
          uploadKey.value ++;
        }
      }).catch((err) => {
        console.log(err)
      })
    }else {
      ElMessage.error(res.data.msg)
    }
  })
  return formData;
}
const handleNodeClick = (data) => {
  const directoryId = data.id;
  fileApi.fileList({"directoryId":directoryId}).then((res) => {
    if (res.data.code === 200){
      fileList.value = res.data.data;
    }
  }).catch((err) => {
    console.log(err)
  })

}
const fileUploadBtn =ref(null);
const handleUploadSuccess = (()=>{
  console.log("clear upload record")
})
const previewFile = ((fileId,fileName)=>{
  let previewUrl = 'http://localhost:18000/course/file/preview/' +  fileId  +'?params=1' + '&fullfilename='+fileName;
  window.open('http://127.0.0.1:8012/onlinePreview?url='+base64UrlEncode(previewUrl));
})
//删除文件
const deleteFile = (fileId)=>{
  fileApi.deleteFile({"fileId":fileId}).then((res) => {
    if (res.data.code === 200){
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      fileApi.fileList({"directoryId":uploadDirectoryId.value}).then((res) => {
        if (res.data.code === 200){
          fileList.value = res.data.data;
          fileUploadBtn.value.clearFiles();
          uploadKey.value ++;
        }
      }).catch((err) => {
        console.log(err)
      })
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}
const base64UrlEncode = ((str) => {
  return btoa(unescape(encodeURIComponent(str)))
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=+$/, '');
})
</script>


<style scoped>
.el-header {
  background-color: #409EFF;
  color: white;
  text-align: center;
  line-height: 60px;
}

.el-main {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>